<?php

/**
 * 角色用户
 *
 * Class UserRoleAction
 *
 * @auth 刘鹏 2017/6/25
 * @modify LLyeap <LL_strive@163.com> 2017-11-25
 */
class UserRoleAction extends Action
{
    private $_serviceRole = null;

    public function __construct()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $this->_serviceRole = D('Role', 'Service');
    }

    /**
     * 所有用户列表
     *
     * @param string $keyword   关键字搜索
     * @param int    $start
     * @param int    $limit
     */
    public function userList($keyword = '', $start = 0, $limit = 10)
    {
        /** 2. 实例化模型 */
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $User = D('customer_user');

        /** 3. 开放平台查询筛选条件 */
        $where["customerId"] = $customerId;
        $where["agent"] = array('eq', 'insideUser');
        $where["status"] = array('eq', 'open');
        if (!empty($keyword)) $where['fullName|phone'] = ['LIKE', '%' . $keyword . '%'];

        /** 4. 查询出符合条件的数据 */
        $arr = $User
            ->where($where)
            ->field('id, fullName, loginName, email, phone')
            ->order('id desc')
            ->limit($start, $limit)
            ->select();
        $content_sql = $User->getLastSql();    // 获取最后一条sql语句, 记录日志用

        /** 5. 返回 */
        if ($arr) {
            Output::instance()->objArray($arr, $User->where($where)->count());
        } else {
            Output::instance()->resultCode(code_success);
        }
    }

    /**
     * 添加运营用户
     * 描述：商家可以添加的为自己工作的运营用户
     * $loginName：账号
     * $password：密码
     */
    public function userAdd($userId = '', $loginName, $password, $email, $address, $phone, $qq, $agent = 'insideUser', $contact = '',$vid='')
    {
//      取session的平台id
        $customerId = Session::$user["customerId"];
        $fullName = Session::$user["fullName"];
//      开放平台 - 查数据库secret
        Session::switchCustomer(0);
//      实例化开发平台数据模型
        $customer_user = D('customer_user');
        Session::switchCustomer($customerId);
//      开放平台查询筛选条件
        $where['email'] = array('eq', "$email");
        $where['customerId'] = array('eq', "$customerId");
        $where['status'] = array('eq', "open");
        if ($userId) {
            $where['id'] = array('neq', $userId);
        } else {
            $data['loginName'] = '';
        }
        $result = $customer_user->where($where)->find();
        if (!empty($result) && empty($userId)) {  //      查询账号是否已经使用
            $return['code'] = '1';
            $return['msg'] = '邮箱已使用';
            if ($agent == 'client') {
                return $return;
            }
            Output::instance()->object($return);
            return;
        }

        $wheres['phone'] = array('eq', $phone);
        $wheres['customerId'] = array('eq', $customerId);
        $wheres['status'] = array('eq', "open");

        if ($userId) {
            $wheres['id'] = array('neq', $userId);
        }
        $results = $customer_user->where($wheres)->find();
        if (!empty($results) && empty($userId)) {//      查询账号是否已经使用
            $return['code'] = '1';
            $return['msg'] = '号码已使用';
            if ($agent == 'client') {
                return $return;
            }
            Output::instance()->object($return);
            return;
        }
//      要入库的的信息

        $data['fullName'] = $loginName;
        $data['email'] = $email;
        $data['phone'] = $phone;
        $data['address'] = $address;
        $data['contact'] = $contact;
        $data['instantNumber'] = $qq;
        $data['vid'] = $vid;
        if (!empty($password)) {
            //      密码加密
            $data['password'] = Encryption::password($password);
        }

        if ($userId) {
            $data['updateTime'] = date("Y-m-d H:i:s");
//          修改
            $result = $customer_user->where("id=$userId")->save($data);
            $content_sql = $customer_user->getLastSql();    //获取最后一条sql语句
            R('Log/add', array('accessControl', '130', '访问控制', op_update, $content_sql, $fullName . '修改' . $loginName . '用户'));
        } else {
            $data['status'] = 'open';
            $data['agent'] = $agent;
            $data['customerId'] = $customerId;
            $time = date("Y-m-d H:i:s");
            $data['registered'] = $time;
//            添加
            $result = $customer_user->add($data);
            $content_sql = $customer_user->getLastSql();    //获取最后一条sql语句
            R('Log/add', array('accessControl', '130', '访问控制', op_add, $content_sql, $fullName . '添加' . $loginName . '用户'));
        }
        if ($agent == 'client') {
            return $result;
        }


        if ($result) {  //      判断是否入库成功
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 获得角色列表 - 该用户已拥有的角色
     *
     * @param $userId
     */
    public function roleList($userId)
    {
        /** 实例化模型 */
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user["id"];
        Session::switchCustomer(0);
        $customer_module_group = M('customer_module_group');
        $Model_Role = M('role');
        $Model_CustomerUserRole = M('customer_user_role');
        Session::switchCustomer($customerId);

        /** 查询筛选条件 */
        $where['manual'] = 1;  // 可被分配
        $where['cid'] = $customerId;  // cid区分平台

//        /** 查询符合自己平台角色 */
//        $gg_where['customerId'] = $customerId;
//        $gg_where['group'] = 'InternalUser';
//        $gg_where['permission'] = 'allow';
//        $gg_module = $customer_module_group->where($gg_where)->find();
//
//        $wmx_where['customerId'] = $customerId;
//        $wmx_where['group'] = 'accessControl';
//        $wmx_where['permission'] = 'allow';
//        $wmx_module = $customer_module_group->where($wmx_where)->find();
//
//        if (!empty($wmx_module) && empty($gg_module)) {
//            $where['auage'] = array('eq', '微梦想');
//        } else if (empty($wmx_module) && !empty($gg_module)) {
//            $where['auage'] = array('eq', '稿稿');
//        } else if (!empty($wmx_module) && !empty($gg_module)) {
//            $where['auage'] = array(array('eq', '微梦想'), array('eq', '稿稿'), 'or');
//        }

        /** 查询数据 */
        $arr = $Model_Role
            ->where($where)
            ->field('id, chineseRole, isSys')
            ->select();
        $data = $Model_CustomerUserRole
            ->where(['userId' => $userId])
            ->getField('roleId, userId');   // => [{roleId: userId}, {}, ...]

        /** 返回 */
        if ($arr) {
            foreach ($arr as $key => $value) {  // 处理该用户是否有该角色
                if (isset($data[ $value['id'] ])) {
                    $arr[$key]['default'] = 1;
                } else {
                    $arr[$key]['default'] = 0;
                }
            }

            Output::instance()->objArray($arr);
        } else {
            Output::instance()->resultCode(code_success);
        }
    }

    /**
     * 给用户赋权
     *
     * @param $userId   用户id
     * @param $roleId   角色id （以逗-号分开）
     */
    public function saveRole($userId, $roleId)
    {
        /** 实例化模型 */
        $customerId = Session::$user["customerId"];
        $fullName = Session::$user["fullName"];
        Session::switchCustomer(0);
        $Model = M();
        $Model_CustomerUserRole = M('customer_user_role');
        $Model_CustomerUser = M('customer_user');
        Session::switchCustomer($customerId);

        // 用于加日志
        $userFullName = $Model_CustomerUser->where(['id' => $userId])->getField('fullName');

        // 删除原有的角色
        $result = $Model_CustomerUserRole->where(['cid' => $customerId, 'userId' => $userId])->delete();

        // 判断是否分配了角色
        if ($roleId == '无角色') {
            Output::instance()->resultCode(code_success);
            return;
        }

        $arr_roleIds = explode(',', $roleId);
        // 把新添加的角色入库
        $data = [];
        foreach ($arr_roleIds as $k_roleId => $v_roleId) {
            $d['cid'] = $customerId;
            $d['roleId'] = $v_roleId;
            $d['userId'] = $userId;

            array_push($data, $d);
        }
        $arr = $Model_CustomerUserRole->addAll($data);

        $content_sql = $Model_CustomerUserRole->getLastSql();    //获取最后一条sql语句
        R('Log/add', array('accessControl', '130', '访问控制', op_update, $content_sql, $fullName . '修改' . $userFullName . '的权限'));

        /** 返回 */
        if ($arr) {
            // 把角色id字符串分割成数组
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 删除运营用户
     * $userId：用户id
     */
    public function deleteRole($userId)
    {
        $where['id'] = array('eq', $userId);
        $customerId = Session::$user["customerId"];
        $fullName = Session::$user["fullName"];
        Session::switchCustomer(0);
        $customer_user = D('customer_user');
        Session::switchCustomer($customerId);
        $save = [
            'status'    => 'close',
            'uopenId'   => null,
            'bindNotice'    => 0
        ];
        $userFullName = $customer_user->where("id=$userId")->getField('fullName', true);

//        删除用户
        $result = $customer_user->where($where)->save($save);

        R('Log/add', array('accessControl', '130', '访问控制', op_delete, $customer_user->getLastSql(), $fullName . '删除' . $userFullName[0] . '用户'));
        if ($result) {
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 修改用户信息
     * $userId：用户id
     */
    public function updateUser($userId)
    {
        $where['a.id'] = array('eq', $userId);
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $customer_user = D('customer_user');
        Session::switchCustomer($customerId);
//        查询出要修改用户的原信息
        $arr = $customer_user->alias('a')
            ->join("wx_mivendor b on b.id = a.vid")
            ->where($where)
            ->field('a.fullName,a.loginName,a.email,a.address,a.phone,a.instantNumber,b.name as vendorName,a.vid')->find();
        if ($arr) {
            Output::instance()->objArray($arr);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /** *********************************** 以下方法用了多层的方法 ************************************* */

    /**
     * 删除一个角色
     *
     * @param $roleId
     */
    public function delRole($roleId)
    {
        /** 删除一个可删除的角色 */
        $result = $this->_serviceRole->delRoleById($roleId);

        /** 返回 */
        Output::instance()->object($result);
    }

    /**
     * 增加一个角色
     *
     * @param     $englishRole  角色英文名
     * @param     $chineseRole  角色中文名
     * @param int $manual       是否可以手动分配: 0-不可以/1-可以
     */
    public function addRole($englishRole, $chineseRole, $manual = 1)
    {
        // 添加角色
        $result = $this->_serviceRole->addRole($englishRole, $chineseRole, $manual);

        Output::instance()->object($result);
    }

    /**
     * 配置一个角色对应的模块和功能点
     *
     * @param        $roleId    角色id
     * @param string $groupIds  角色对应的模块
     * @param string $actionIds 角色对应的功能点
     */
    public function updateRoleGroupAction($roleId, $groupIds = '', $actionIds = '')
    {
        $arr_groupIds = explode(',', $groupIds);
        $arr_actionIds = explode(',', $actionIds);
        // 处理actions
        $resultAction = $this->_serviceRole->updateRoleAction($roleId, $arr_actionIds);
        if ($resultAction['code'] != 0) {
            Output::instance()->object($resultAction);
            return;
        }
        // 处理groups
        $resultGroup = $this->_serviceRole->updateRoleGroup($roleId, $arr_groupIds);
        if ($resultGroup['code'] != 0) {
            Output::instance()->object($resultGroup);
            return;
        }

        // 返回
        $resultGroup['data'] = array_merge($resultGroup['data'], $resultAction['data']);
        Output::instance()->object($resultGroup);
    }

    /**
     * 获得角色列表
     *
     * @param string $keyword   关键字查询
     * @param string $order
     * @param string $orderBy
     * @param int    $start
     * @param int    $limit
     */
    public function getRoles($keyword = '', $order = 'id', $orderBy = 'desc', $start = 0, $limit = 10)
    {
        // 查询角色列表
        $result = $this->_serviceRole->getRoles($keyword, $order, $orderBy, $start, $limit);

        Output::instance()->object($result);
    }

    /**
     * 获得指定角色当前的模块配置
     *
     * @param $roleId   角色id
     */
    public function getRoleById($roleId)
    {
        // 查询角色对应的模块和功能点的配置情况
        $result = $this->_serviceRole->getRoleById($roleId);

        Output::instance()->object($result);
    }

    /**
     * 显示指定角色当前的模块功能点的配置
     *
     * @param $roleId
     */
    public function showRoleById($roleId)
    {
        // 查询当前这个角色选中的模块和功能点的配置情况
        $result = $this->_serviceRole->showRoleById($roleId);

        Output::instance()->object($result);
    }

}